package nuc.edu.tlias.Filter;

import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import nuc.edu.tlias.utils.CurrentHolder;
import nuc.edu.tlias.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();

        if (requestURI.contains("login")){
            // 放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        String token = request.getHeader("token");

        if ( token == null||token.isEmpty() ){
            response.setStatus(401);
            return;
        }

        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer empid = Integer.valueOf(claims.get("id").toString());

            CurrentHolder.setCurrentId(empid);
            //当前获取到的id是
            log.info("当前获取到的id是"+empid);
        } catch (Exception e) {
            // 令牌错误
            response.setStatus(401);
            return;
        }

        // 放行
        filterChain.doFilter(request,response);

        CurrentHolder.remove();

    }
}
